import { VipLevel } from '../types/vip';
import type { User, VipInfo } from '../types/vip';
import { mockCoupons } from '../data/vipPackages';

/**
 * 检查用户VIP状态是否激活
 * @param vipInfo VIP信息
 * @returns 是否为激活的VIP用户
 */
export const isVipActive = (vipInfo: VipInfo | undefined): boolean => {
  if (!vipInfo) {
    return false;
  }
  
  // 检查VIP等级和激活状态
  if (!vipInfo.isActive || vipInfo.level === VipLevel.NORMAL) {
    return false;
  }
  
  // 检查VIP是否过期
  if (vipInfo.expireDate) {
    const now = new Date();
    const expireDate = new Date(vipInfo.expireDate);
    if (now > expireDate) {
      return false;
    }
  }
  
  return true;
};

/**
 * 获取用户VIP等级
 * @param vipInfo VIP信息
 * @returns VIP等级
 */
export const getVipLevel = (vipInfo: VipInfo | undefined): VipLevel => {
  if (!vipInfo || !isVipActive(vipInfo)) {
    return VipLevel.NORMAL;
  }
  return vipInfo.level;
};

/**
 * 从User对象获取VIP等级（兼容旧接口）
 * @param user 用户信息
 * @returns VIP等级
 */
export const getUserVipLevel = (user: User | null): VipLevel => {
  return getVipLevel(user?.vipInfo);
};

/**
 * 计算VIP折扣价格
 * @param originalPrice 原价
 * @param vipInfo VIP信息
 * @param isFullBuild 是否为整机（整机可能有额外折扣）
 * @returns 折后价格
 */
export const calculateVipPrice = (originalPrice: number, vipInfo: VipInfo | undefined, isFullBuild = false): number => {
  if (!isVipActive(vipInfo) || !vipInfo) {
    return originalPrice;
  }
  
  let discountRate = vipInfo.discountRate;
  
  // 整机额外折扣
  if (isFullBuild) {
    switch (vipInfo.level) {
      case VipLevel.SILVER:
        discountRate *= 0.95; // 额外5%折扣
        break;
      case VipLevel.GOLD:
        discountRate *= 0.90; // 额外10%折扣
        break;
      case VipLevel.PLATINUM:
        discountRate *= 0.85; // 额外15%折扣
        break;
    }
  }
  
  // 确保折扣后价格不为负
  const discountedPrice = Math.max(0, originalPrice * discountRate);
  // 保留两位小数
  return Math.round(discountedPrice * 100) / 100;
};

/**
 * 搜索配件优惠券
 * @param productName 产品名称或关键词
 * @param vipInfo VIP信息（需要VIP权限）
 * @returns 优惠券列表
 */
export const searchCoupons = (productName: string, vipInfo: VipInfo | undefined): typeof mockCoupons => {
  // 检查用户是否有权限使用优惠券搜索功能
  const vipLevel = getVipLevel(vipInfo);
  if (vipLevel === VipLevel.NORMAL || vipLevel === VipLevel.BRONZE) {
    return [];
  }
  
  // 模拟搜索优惠券（实际应用中可能会调用API）
  const keyword = productName.toLowerCase();
  return mockCoupons.filter(coupon => 
    coupon.productName.toLowerCase().includes(keyword)
  );
};

/**
 * 从localStorage获取用户信息（包含VIP信息）
 * @returns 用户信息
 */
export const getUserWithVipInfo = (): User | null => {
  try {
    const userData = localStorage.getItem('user');
    const vipData = localStorage.getItem('vipInfo');
    
    if (userData) {
      const user = JSON.parse(userData) as User;
      if (vipData) {
        user.vipInfo = JSON.parse(vipData) as VipInfo;
      }
      return user;
    }
    return null;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
};

/**
 * 格式化VIP等级显示名称
 * @param level VIP等级
 * @returns 显示名称
 */
export const formatVipLevel = (level: VipLevel): string => {
  const levelMap: Record<VipLevel, string> = {
    [VipLevel.NORMAL]: '普通用户',
    [VipLevel.BRONZE]: '青铜会员',
    [VipLevel.SILVER]: '白银会员',
    [VipLevel.GOLD]: '黄金会员',
    [VipLevel.PLATINUM]: '铂金会员'
  };
  return levelMap[level] || '普通用户';
};

/**
 * 获取VIP等级对应的颜色
 * @param level VIP等级
 * @returns CSS颜色值
 */
export const getVipLevelColor = (level: VipLevel): string => {
  const colorMap: Record<VipLevel, string> = {
    [VipLevel.NORMAL]: '#999999',
    [VipLevel.BRONZE]: '#CD7F32',
    [VipLevel.SILVER]: '#C0C0C0',
    [VipLevel.GOLD]: '#FFD700',
    [VipLevel.PLATINUM]: '#E5E4E2'
  };
  return colorMap[level] || '#999999';
};

/**
 * 保存用户VIP信息到本地存储
 * @param user 用户信息
 * @param vipInfo VIP信息
 */
export const saveVipInfo = (user: User, vipInfo: VipInfo): void => {
  if (user.email) {
    localStorage.setItem(`vip_${user.email}`, JSON.stringify(vipInfo));
    // 同时更新用户对象中的VIP信息
    const updatedUser = { ...user, vipInfo };
    localStorage.setItem('user', JSON.stringify(updatedUser));
  }
};